//
//  JPUserInfoViewModel.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 16/9/22.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit

class JPUserInfoViewModel: NSObject {
    
    static let sharedUserInfoViewModel: JPUserInfoViewModel = JPUserInfoViewModel()
    
    var userInfo: JPUserInfoModel? {
        return JPUserInfoModel.decodeUserInfo()
    }
    
    var isLogin: Bool {
        
        return accessToken != nil
    }
    
    var accessToken: String? {
        
        let token = userInfo?.access_token
        
        if token != nil {
            
            if userInfo?.expiresDate?.compare(Date()) == .orderedDescending {
                return token
            }else {
                return nil
            }
        }else {
            return nil
        }
    }
    
    ///请求用户信息
    func requestUserInfo(userInfo: JPUserInfoModel, callBack: @escaping (Bool) -> ()) {
        
        JPNetworkTool.sharedNetworkTool.requestUserInfo(accessToken: userInfo.access_token!, uid: Int(userInfo.uid), callback: { (response, error) in
            
            if error != nil {
                print("请求用户信息失败")
                callBack(false)
                return
            }
            
            guard let dict = response as? [String: Any] else {
                print("请求的用户信息不是一个正确的字典")
                callBack(false)
                return
            }
            
            let name = dict["name"]
            let avatar_large = dict["avatar_large"]
            
            userInfo.name = name as? String
            userInfo.avatar_large = avatar_large as? String
            
            userInfo.encodeUserInfo()
            callBack(true)
        })
    }
    
    ///请求授权许可证
    func requestAccessToken(code: String, callBack: @escaping (Bool) -> ()) {
        
        JPNetworkTool.sharedNetworkTool.requestAccessToken(code: code, callback: { (response, error) in
            
            if error != nil {
                print("请求access_token失败")
                print(error)
                callBack(false)
                return
            }
            
            guard let dict = response as? [String: Any] else {
                callBack(false)
                return
            }
            
            let userInfo = JPUserInfoModel(dict: dict)
            
            self.requestUserInfo(userInfo: userInfo, callBack: callBack)
        })
    }

}
